package com.rayboot.footpoint.activity;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.rayboot.footpoint.R;
import com.rayboot.footpoint.utils.FootLog;
import com.rayboot.footpoint.utils.FootpointConstant;

public class FindLocationOnMapActivity extends MapActivity implements
		OnClickListener {
	private MapView map = null;
	private MyLocationOverlay me = null;
	private Button btnOk = null;
	private Button btnCancel = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_find_location_on_map);

		map = (MapView) findViewById(R.id.mvFMMap);

		GeoPoint point = getPoint(
				getIntent().getDoubleExtra(FootpointConstant.EXTRA_LATITUDE,
						30.659259),
				getIntent().getDoubleExtra(FootpointConstant.EXTRA_LONGITUDE,
						104.065762));

		map.getController().setCenter(point);
		map.getController().animateTo(point);
		map.getController().setZoom(17);
		map.setBuiltInZoomControls(true);

		Drawable marker = getResources().getDrawable(
				R.drawable.pin_pointer_center_small);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight());

		map.getOverlays().add(new SitesOverlay(marker));

		me = new MyLocationOverlay(this, map);
		map.getOverlays().add(me);

		btnOk = (Button) findViewById(R.id.btnFMOK);
		btnCancel = (Button) findViewById(R.id.btnFMCancel);
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();

		me.enableCompass();
	}

	@Override
	public void onPause() {
		super.onPause();

		me.disableCompass();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return (false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_S) {
			map.setSatellite(!map.isSatellite());
			return (true);
		} else if (keyCode == KeyEvent.KEYCODE_Z) {
			map.displayZoomControls(true);
			return (true);
		}

		return (super.onKeyDown(keyCode, event));
	}

	private GeoPoint getPoint(double lat, double lon) {
		return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
	}

	private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> items = new ArrayList<OverlayItem>();
		private Drawable marker = null;
		private OverlayItem inDrag = null;
		private ImageView dragImage = null;
		private int xDragImageOffset = 0;
		private int yDragImageOffset = 0;
		private int xDragTouchOffset = 0;
		private int yDragTouchOffset = 0;
		private Point centerPoint = null;
		private String title = null;
		private String snippet = null;

		public SitesOverlay(Drawable marker) {
			super(marker);
			this.marker = marker;

			dragImage = (ImageView) findViewById(R.id.drag);
			xDragImageOffset = dragImage.getDrawable().getIntrinsicWidth() / 2;
			yDragImageOffset = dragImage.getDrawable().getIntrinsicHeight();

			items.add(new OverlayItem(getPoint(30.659259, 104.065762), "UN",
					"United Nations"));

			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return (items.get(i));
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			boundCenterBottom(marker);
			if (inDrag == null) {

				Paint paint = new Paint();
				if (centerPoint == null) {
					centerPoint = new Point();
					// 将经纬度转换成实际屏幕坐标
					mapView.getProjection().toPixels(mapView.getMapCenter(),
							centerPoint);
				}
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.pin_pointer_center_small);
				canvas.drawBitmap(bmp, centerPoint.x - bmp.getWidth() / 2,
						centerPoint.y - bmp.getHeight(), paint);
			}
		}

		@Override
		public int size() {
			return (items.size());
		}

		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			final int action = event.getAction();
			final int x = (int) event.getX();
			final int y = (int) event.getY();
			boolean result = false;
			if (action == MotionEvent.ACTION_DOWN) {

				if (items.size() == 0) {
					items.add(new OverlayItem(mapView.getMapCenter(), title,
							snippet));
				}

				for (OverlayItem item : items) {
					Point p = new Point(0, 0);

					map.getProjection().toPixels(item.getPoint(), p);

					if (hitTest(item, marker, x - p.x, y - p.y)) {
						result = true;
						inDrag = item;
						items.remove(inDrag);
						populate();

						xDragTouchOffset = 0;
						yDragTouchOffset = 0;

						setDragImagePosition(p.x, p.y);
						dragImage.setVisibility(View.VISIBLE);

						xDragTouchOffset = x - p.x;
						yDragTouchOffset = y - p.y;

						break;
					} else {
						snippet = items.get(0).getSnippet();
						title = items.get(0).getTitle();
						items.clear();
					}
				}
			} else if (action == MotionEvent.ACTION_MOVE) {
				if (inDrag != null) {
					setDragImagePosition(x, y);
					result = true;
				} else {
				}
			} else if (action == MotionEvent.ACTION_UP) {
				if (inDrag != null) {
					dragImage.setVisibility(View.GONE);

					GeoPoint pt = map.getProjection().fromPixels(
							x - xDragTouchOffset, y - yDragTouchOffset);
					OverlayItem toDrop = new OverlayItem(pt, inDrag.getTitle(),
							inDrag.getSnippet());

					items.add(toDrop);

					map.getController().setCenter(pt);
					map.getController().animateTo(pt);

					populate();

					inDrag = null;
					result = true;
				}
			}

			return (result || super.onTouchEvent(event, mapView));
		}

		private void setDragImagePosition(int x, int y) {
			RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) dragImage
					.getLayoutParams();

			lp.setMargins(x - xDragImageOffset - xDragTouchOffset, y
					- yDragImageOffset - yDragTouchOffset, 0, 0);
			dragImage.setLayoutParams(lp);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.equals(btnOk)) {
			setResult(RESULT_OK);
		} else if (v.equals(btnCancel)) {
			setResult(RESULT_CANCELED);
		}
		finish();
	}
}
